<template>
	<view class="study-group-container">
		<!-- 顶部导航栏 -->
		<public-module leftIcon="arrow-left" title="学习小组" />

		<!-- 搜索和新增 -->
		<view class="search-add-container">
			<view class="search-box">
				<u-search v-model="searchId" placeholder="直接粘贴邀请口令即可" @search="searchGroup"
					@custom="searchGroup"></u-search>
			</view>
			<view class="add-btn" @click="toggleCreateGroupArea">
				<u-icon name="plus" color="#ffffff" size="20"></u-icon>
			</view>
		</view>

		<!-- 新增：小组使用说明 -->
		<view class="group-instructions">
			<text>点击＋号即可创建小组，在小组详情页可以邀请别人，复制邀请口令到搜索栏，点击搜索，即可加入。</text>
		</view>

		<!-- 创建学习小组区域 -->
		<view class="add-group-area" v-if="showCreateGroupArea">
			<view class="modal-title">新建学习小组</view>
			<u-form :model="groupForm" :rules="rules" ref="groupForm" labelPosition="top" labelWidth="100%">
				<u-form-item label="小组名称" prop="name" borderBottom>
					<u-input v-model="groupForm.groupName" placeholder="请输入小组名称" />
				</u-form-item>
				<u-form-item label="小组公告" prop="notice" borderBottom>
					<textarea v-model="groupForm.groupNotice" class="punch-textarea" placeholder="请输入小组公告">
                    </textarea>
				</u-form-item>
			</u-form>
			<view class="modal-btns">
				<u-button @click="toggleCreateGroupArea">取消</u-button>
				<u-button type="primary" @click="createGroup">确定</u-button>
			</view>
		</view>

		<!-- 小组列表 -->
		<view class="group-list" v-if="searchResults.length === 0">
			<view v-for="group in studyGroups" :key="group.id" class="group-card" @click="goToGroupDetail(group)">
				<view class="group-info">
					<view class="group-header">
						<text class="group-name">{{group.groupName}}</text>
						<text class="group-member-count">{{group.memberCount}}人</text>
					</view>
					<view class="group-stats">
						<view class="stat-item">
							<text class="stat-label">今日打卡</text>
							<text class="stat-value">{{group.todayMarkCount}}/{{group.memberCount}}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">专注时长</text>
							<text class="stat-value">{{group.todayMarkCount}}分钟</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">模考完成</text>
							<text class="stat-value">{{group.todayMarkCount}}次</text>
						</view>
					</view>
				</view>
				<view class="group-arrow">
					<u-icon name="arrow-right" color="#666666" size="24"></u-icon>
				</view>
			</view>
		</view>

		<!-- 暂无数据提示 -->
		<view class="empty-state" v-if="studyGroups.length === 0 && searchResults.length === 0">
			<text class="empty-text">暂无学习小组</text>
		</view>

		<!-- 新增：搜索结果区域 -->
		<view class="search-result-container" v-if="searchResults.length > 0">
			<view class="search-title">搜索结果</view>
			<view class="search-group-card" v-for="group in searchResults" :key="group.id">
				<view class="search-group-info">
					<text class="search-group-name">{{group.groupName}}</text>
				</view>
				<!-- 修改按钮文本 -->
				<button type="primary" size="mini" @click="joinGroup(group)"
					class="join-btn custom-join-btn">加入</button>
			</view>
		</view>
	</view>
</template>

<style>
	/* 新增：小组使用说明样式 */
	.group-instructions {
		padding: 0 15px;
		margin-bottom: 15px;
		font-size: 14px;
		color: #666;
	}
</style>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		groupList,
		groupAdd,
		groupEdit,
		groupkDelete,
		groupDetail,
		groupMemberAdd,
		msgSecCheck
	} from "@/config/api.js";

	export const groupFormRules = {
		groupName: [{
			required: true,
			message: '请输入小组名称',
			trigger: ['blur', 'change']
		}],
		groupNotice: [{
			required: true,
			message: '请输入小组公告',
			trigger: ['blur', 'change']
		}]
	};

	export default {
		data() {
			return {
				studyGroups: [], // 学习小组列表
				searchId: '', // 搜索ID
				showCreateGroupArea: false, // 显示创建学习小组区域
				groupForm: {
					groupName: '',
					groupNotice: ''
				},
				groupUserForm: {
					id: '',
				},
				rules: groupFormRules,
				searchResults: [] // 搜索结果
			}
		},
		onLoad() {
			this.getStudyGroups()
		},
		methods: {
			// 获取学习小组列表
			async getStudyGroups() {
				try {
					const res = await groupList();
					if (res.code === 200) {
						// 将后端返回的数据赋值给 studyGroups
						this.studyGroups = res.data;
						console.log(this.studyGroups)
					}
				} catch (error) {
					console.error('获取学习小组列表失败：', error)
					uni.showToast({
						title: '获取学习小组列表失败',
						icon: 'none'
					})
				}
			},

			// 跳转到小组详情页
			goToGroupDetail(group) {
				uni.navigateTo({
					url: `/pages/studygroup/detail?group=${encodeURIComponent(JSON.stringify(group))}`
				})
			},

			// 切换创建学习小组区域的显示状态
			toggleCreateGroupArea() {
				this.showCreateGroupArea = !this.showCreateGroupArea;
			},

			// 创建小组
			async createGroup() {
				try {
					await this.$refs.groupForm.validate();
					console.log('表单验证通过');
					const checkRes = await msgSecCheck({
						content: [this.groupForm.groupName,
								this.groupForm.groupNotice
							]
							.filter(Boolean)
							.join('\n') // 这里已经正确处理了换行符
					});
					if (checkRes.errcode !== 0) {
						return uni.$u.toast('内容包含违规信息，请修改');
					}
					const res = await groupAdd(this.groupForm);

					uni.showToast({
						title: '创建成功',
						icon: 'success'
					})

					this.showCreateGroupArea = false
					this.groupForm.groupName = ''
					this.groupForm.groupNotice = ''
					this.getStudyGroups() // 刷新列表
				} catch (error) {
					console.error('创建学习小组失败：', error)
					uni.showToast({
						title: '请完善小组信息',
						icon: 'none'
					})
				}
			},

			// 搜索小组
			async searchGroup() {
				if (!this.searchId) {
					this.searchResults = [];
					this.getStudyGroups();
					return;
				}

				try {
					const idIndex = this.searchId.indexOf('ID');
					const startIndex = idIndex + 2;
					const endIndex = startIndex + 32;
					const groupId = this.searchId.slice(startIndex, endIndex);
					console.log(groupId);
					const res = await groupDetail(groupId);
					if (res.code === 200) {
						this.searchResults = [res.data];
						console.log(this.searchResults);
					}
				} catch (error) {
					console.error('搜索小组失败：', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				}
			},
			// 加入小组
			async joinGroup(group) {
				try {
					this.groupUserForm.groupId = group.id;
					console.log(this.groupUserForm.groupId)
					const res = await groupMemberAdd(this.groupUserForm);
					uni.showToast({
						title: '已申请加入小组',
						icon: 'success'
					})
					// 刷新学习小组列表
					this.getStudyGroups();
					// 清空搜索结果
					this.searchResults = [];
				} catch (error) {
					console.error('加入小组失败：', error)
					uni.showToast({
						title: '加入小组失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style>
	.study-group-container {
		min-height: 100vh;
		background-color: #f8f8f8;
		padding-bottom: 20px;
	}

	.group-list {
		padding: 15px;
	}

	.group-card {
		background-color: #ffffff;
		border-radius: 12px;
		padding: 15px;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
	}

	.group-info {
		flex: 1;
	}

	.group-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;
	}

	.group-name {
		font-size: 18px;
		font-weight: bold;
		color: #333;
	}

	.group-member-count {
		font-size: 14px;
		color: #666;
	}

	.group-stats {
		display: flex;
		justify-content: space-between;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.stat-label {
		font-size: 12px;
		color: #999;
		margin-bottom: 5px;
	}

	.stat-value {
		font-size: 14px;
		color: #333;
		font-weight: 500;
	}

	.group-arrow {
		margin-left: 15px;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 100px;
	}

	.empty-text {
		margin-top: 10px;
		color: #999;
		font-size: 14px;
	}

	.search-add-container {
		padding: 15px;
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.search-box {
		flex: 1;
	}

	.add-btn {
		width: 40px;
		height: 40px;
		background-color: #4A89DC;
		border-radius: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.add-group-area {
		background-color: #fff;
		width: 80vw;
		margin: 0 auto;
		padding: 20px;
		border-radius: 12px;
		margin-bottom: 15px;
	}

	.modal-title {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 20px;
	}

	.modal-btns {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
		gap: 15px;
	}

	.search-result-container {
		padding: 15px;
		background-color: #f5f7fa;
		margin-top: 10px;
		border-radius: 8px;
	}

	.search-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 10px;
	}

	.search-group-card {
		background-color: #fff;
		border-radius: 8px;
		padding: 12px 15px;
		margin-bottom: 10px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		transition: all 0.3s ease;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.search-group-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	.search-group-info {
		flex: 3;
	}

	.search-group-name {
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}

	.join-btn {
		/* 调整按钮宽度 */
		width: 50px !important;
		margin-left: 10px;
		flex: 1;
	}

	.custom-join-btn {
		background-color: #28a745;
		border-color: #28a745;
		color: #ffffff;
		transition: all 0.3s ease;
	}

	.custom-join-btn:hover {
		background-color: #218838;
		border-color: #1e7e34;
	}

	.punch-textarea {
		width: 100%;
		height: 120px;
		font-size: 14px;
		border: 1px solid rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		padding: 10px;
		margin-bottom: 10px;
	}
</style>